package com.kaesar.leetcode.LeetCode_051_100;

import com.kaesar.leetcode.ListNode;

public class LeetCode_082 {
    public static ListNode deleteDuplicates(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = new ListNode(-1);
        ListNode last = newHead, cur = head;
        while (cur != null) {
            // 当前节点是否是重复的标识
            boolean isRepeated = false;
            ListNode next = cur.next;
            // 找到下一个跟cur节点的数字不同的节点，并且判断当前节点是否是重复的
            while (next != null && next.val == cur.val) {
                isRepeated = true;
                next = next.next;
            }
            if (isRepeated) {
                // 如果当前节点是重复的，则跳过这个重复节点
                cur = next;
            } else {
                // 如果当前节点不是重复的，则作为last的下一个节点
                last.next = new ListNode(cur.val);
                last = last.next;
                cur = next;
            }
        }
        return newHead.next;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(2);

        ListNode result = deleteDuplicates(head);
        while (result != null) {
            System.out.print(result.val + " ");
            result = result.next;
        }
    }
}
